import axios from "axios";

import {ElMessage} from "element-plus";
import store from '@/store'


const defaultError = () => ElMessage.error('发生了一些错误，请联系管理员')
const defaultFailure = () => ElMessage.warning("失败")


/*
    自定义状态码
    SUCCESS(200, "ok"),
    PARAMS_ERROR(40000, "请求参数错误"),
    NOT_LOGIN_ERROR(40100, "未登录"),
    NO_AUTH_ERROR(40101, "无权限"),
    WRONG_PASSWORD(40001,"密码错误"),
    NOT_FOUND_ERROR(40400, "请求数据不存在"),
    FORBIDDEN_ERROR(40300, "禁止访问"),
    SYSTEM_ERROR(50000, "系统内部异常"),
    OPERATION_ERROR(50001, "操作失败");
*/

//login使用的post
function postWithToken(url, data, success, failure = defaultFailure, error = defaultError) {
    axios.post(url, data, {
        headers: store.state.authHeader
    }).then(({data}) => {
        if (data.code === 200) {
            success(data.data, data.code, data.message);
        } else if(data.code >=40000&& data.code<= 60000){
            failure(data.data,data.code,data.message);
        }
    }).catch(error);
}


function getWithToken(url,  success, failure = defaultFailure, error = defaultError){
    axios.get(url, {
        headers: store.state.authHeader,
    }).then(({data}) => {
        if (data.code === 200) {
            success(data.data, data.code, data.message);
        } else if(data.code >=40000&& data.code<= 60000){
            failure(data.data, data.code, data.message);
        }
    }).catch(error);
}




export {postWithToken,getWithToken}



